/** ANAYLSIS_56.C
 *  Analyse Macros zum F-Praktikumsversuch 56: Polarisationsverschränkte Photonenpaare
 * 
 *  date:   12.10.2011
 *  author: Ch.Weinsheimer 
 */


/// Definiere Sin^2 Fit-Funktion für Korrelationsmessung
double sq_sine(double* vars, double* pars) {
  return pars[0]*TMath::Power(TMath::Sin(pars[1]*vars[0]+pars[2]),2.0) + pars[3];
}


/// Plotten der Correlations-Kurven
void correlation(char* filename, Double_t amp, Double_t fac, Double_t pha, Double_t off, Int_t RBFact = 1)
{
    int const N = 72;    
    double const ANGLE_ERROR = 2.0;

    // File Opening
    FILE* file = fopen(filename, "r");
    char dummy[12];
    // Lese Daten
    Double_t angle[N],coinc[N],dAngle[N],dCoinc[N];
    for(Int_t i=0; i < N; i++){
        fscanf(file, "%lf %lf %lf %lf %lf %lf", &angle[i],&dummy,&coinc[i],&dummy,&dummy,&dummy);
        dAngle[i] = ANGLE_ERROR;
	dCoinc[i] = TMath::Sqrt(coinc[i]);
    }

    fclose(file);

    // Erzeuge TGraph repsaesentation
    TGraphErrors* Graph = gROOT->FindObject("Graph");
    if(!Graph) Graph = new TGraphErrors(N,angle,coinc,dAngle,dCoinc);
    else Graph->Reset("M");

    // Erzeuge Fit-Funktion
    TF1 fitfunc("fitfunc",sq_sine,0,355,4);
    double amplitude = amp; double factor = fac; double phase = pha; double offset = off;
    fitfunc.SetParameters(amplitude, factor, phase, offset);
    fitfunc.SetParNames("Amplitude", "Factor", "Phase", "Offset");
    fitfunc.SetLineColor(kBlue);
    
    //Perform Fit
    Graph->Fit(&fitfunc);

    // Hole Fit-Resultate
    TVirtualFitter *fit = TVirtualFitter::GetFitter();
    fit->PrintResults(2,0.);
    TMatrixD *covMatrix = new TMatrixD(fitfunc.GetNpar(),fitfunc.GetNpar(),fit->GetCovarianceMatrix());
    covMatrix->Print();

    // Erzeuge das Fenster
    TCanvas* Canva = gROOT->Find Object("Canva");
    if(!Canva) Canva = new TCanvas("Canva", "Correlation", 800, 600);
    else Canva->Clear();
    Canva->cd(1); // Waehle das Feld an

    
    // Setze Beschriftungen und Styles
    gROOT->SetStyle("Plain");
    gStyle->SetOptFit(111);
    Graph->SetMarkerStyle(2);
    Graph->SetTitle("Correlation Plot");
    Graph->GetXaxis()->SetTitle("angle [deg]");
    Graph->GetYaxis()->SetTitle("coincidence count rate [(10 s)^-1]");
    fitfunc.SetLineWidth(3);
    fitfunc.SetLineColor(kBlue);
    fitfunc.SetLineStyle(1);

    // Male Graph
    Graph->DrawClone("APE");    

}
